import axios from 'axios'
import { Message, Loading } from 'element-ui'
import store from '@/store'

const instance = axios.create({
  baseURL: '/api', // 请求统一的前缀
  timeout: 20000,
  headers: {
    'X-Requested-With': 'XMLHttpRequest',
    'Content-Type': 'application/json; charset=UTF-8',
    'Access-Control-Allow-Origin': '*',
    dataType: 'json'
  }
})

function _http(method) {
  return (resPath, params, options = {}) => {
    const {
      isShowLoading = false, // 是否显示loading
      loadingText = 'loading ...', // 显示loading提示文字
      loadingTarget = '.main-container', // 挂载的dom节点
      isShowTips = true // 是否显示错误提示气泡
    } = options

    let errShowTips = true; // 系统错误提示

    const loadingInstance = isShowLoading ? Loading.service({
      lock: true,
      text: loadingText,
      target: loadingTarget,
      fullscreen: true
    }) : null

    return instance[method](resPath, params)
      .then(res => {
        loadingInstance && loadingInstance.close()

        if (!res) {
          return Message.error('No response from API:' + resPath)
        }

        const { data } = res
        if (data.flag === 'S') {
          return Promise.resolve(data)
        }
        
        // 后端返回code判断登录失效  删除token然后刷新页面返回登录
        if (data.code === 'THOTH006') {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        }

        errShowTips && isShowTips && Message({
          message: data.msg || 'request error',
          type: 'error',
          offset: 60
        })

        errShowTips = false  // 非系统错误提示已经弹窗了
        return Promise.reject(new Error(data.msg || 'Error'))
      })
      .catch(error => {
        loadingInstance && loadingInstance.close()
        errShowTips && isShowTips && Message({
          message: error.message || 'request error',
          type: 'error',
          offset: 60
        })
        return Promise.reject(error)
      })
  }
}

export default {
  get: _http('get'),
  post: _http('post')
}

